package com.study.sqlSession;

import com.study.pojo.Configuration;
import com.study.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        // 将要完成对simpleExecutor里的query方法的调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objectList = selectList(statementId, params);
        if (objectList.size() == 1) {
            return (T) objectList.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者返回结果过多");
        }
    }

    @Override
    public int update(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        return simpleExecutor.update(configuration, mappedStatement, params);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) throws Exception {
        // 使用JDK动态代理为Dao接口生成代理对象，并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 底层还是去执行JDBC代码
                // 根据不同情况，来调用selectList或selectOne

                // 1. 准备参数：statementId

                // 方法名
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;

                MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
                if (mappedStatement == null) {
                    throw new RuntimeException("当前[statementId:" + statementId + "]不合法");
                }

                // 2. 准备参数：params=args

                // 3. 获取被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                switch (mappedStatement.getSqlType()) {
                    case SELECT:
                        // 判断是否进行了泛型类型参数化
                        if (genericReturnType instanceof ParameterizedType) {
                            return selectList(statementId, args);
                        } else {
                            return selectOne(statementId, args);
                        }
                    case INSERT:
                    case DELETE:
                    case UPDATE:
                        return update(statementId, args);
                    default:
                        throw new RuntimeException("当前不支持该类型的sql");
                }
            }
        });
        return (T) proxyInstance;
    }
}
